package com.qinsoft.frame.taobao.onsale;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.qinsoft.business.onsale.bean.OnSale;
import com.qinsoft.business.onsale.dao.OnSaleDao;
import com.qinsoft.business.onsalelog.bean.OnSaleLog;
import com.qinsoft.business.onsalelog.dao.OnSaleLogDao;
import com.qinsoft.business.task.bean.Task;
import com.qinsoft.business.task.dao.TaskDao;
import com.qinsoft.business.user.bean.User;
import com.qinsoft.business.user.dao.UserDao;
import com.qinsoft.frame.constants.QinCodeConstants;
import com.qinsoft.frame.exception.ApiException;
import com.qinsoft.frame.taobao.task.TaskException;
import com.qinsoft.frame.utils.TaobaoInter;
import com.taobao.api.domain.Item;
import com.taobao.api.response.ItemUpdateDelistingResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;


public class OnSaleTask implements Runnable
{
    private final String SALE = "sale";

    private Integer index = 0;
    private TaskDao taskDao = new TaskDao();
    private OnSaleLogDao logDao = new OnSaleLogDao();
    private List<OnSale> list = new ArrayList<OnSale>();
    
    @Override
    public void run()
    {
        while (true)
        {
            try
            {
                start();
                Thread.sleep(QinCodeConstants.SALE_FIXED_TIME);
            }
            catch (Exception e)
            {
                TaskException.getResultMessage(e);
            }
        }
    }
    
    /**
     * 初始化
     */
    public void init()
    {
        index = 0;
        OnSaleDao saleDao = new OnSaleDao();
        if(taskDao.exist(SALE))
        {
            Task tasks = taskDao.select(SALE);
            index = tasks.getNowPosition();
        }
        list = saleDao.selectAll(index);
    }
    
    /**
     * 具体执行任务
     */
    public void start()
    {
        Date date = new Date();
        init();
        for(int i=0; list!=null && i<list.size(); i++,index++)
        {
            try
            {
                Calendar calendar = Calendar.getInstance();
                User user = UserDao.getUser(list.get(i).getNick());
                //权限控制
                char[] permit = user.getPermit().toCharArray();
                if(user.getDeadline().before(date) || permit[2]=='0'){
                    continue;
                }
                //根据计划，设置上下架商品数
                String plan[][] = list.get(i).getPlan();
                int week = calendar.get(Calendar.WEDNESDAY)-1;
                int day = calendar.get(Calendar.HOUR_OF_DAY)-1;
                
                String size = plan[week][day];
                if(size==null || size.equals("0")){
                    continue;
                }
                String tql = "select num_iid,num from taobao.items.onsale.get where page_size="+size;
                ItemsOnsaleGetResponse response = TaobaoInter.sendInter(tql, user.getToken(), ItemsOnsaleGetResponse.class);
                //TODO更新自动计划
                if(response.getTotalResults()!=list.get(i).getItemNum()){
                    
                }
                List<Item> list = response.getItems();
                //进行上下架
                for(Item item : list){
                    try{
                        tql = "select * from taobao.item.update.delisting where num_iid="+item.getNumIid();
                        TaobaoInter.sendInter(tql, user.getToken(), ItemUpdateDelistingResponse.class);
                        tql = "select * from taobao.item.update.listing where num_iid="+item.getNumIid()+" and num="+item.getNum();
                        TaobaoInter.sendInter(tql, user.getToken(), ItemUpdateDelistingResponse.class);
                    }
                    catch (ApiException e) {
                        //记录日志
                        OnSaleLog log = new OnSaleLog(user.getNick(), item.getNumIid(), e);
                        logDao.save(log);
                    }
                }
                //记录日志
                OnSaleLog log = new OnSaleLog(user.getNick(), size, "成功调整"+size+"个商品的上下架时间");
                logDao.save(log);
            }
            catch (Exception e)
            {
                TaskException.getResultMessage(this.getClass().toString()+".start("+ list.get(i).getNick() +")",e);
            }
        }
    }
    
    /**
     * 当服务器关闭时调用
     */
    public void stop()
    {
        Task task = new Task(SALE, 0, index, list.size());
        taskDao.insert(task);
    }
}
